/*
 * Copyright 2019 bingoogolapple
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.bingoogolapple.transformerstip.demo;

import cn.bingoogolapple.transformerstip.LogUtils;
import cn.bingoogolapple.transformerstip.TransformersTip;
import cn.bingoogolapple.transformerstip.demo.ResourceTable;
import cn.bingoogolapple.transformerstip.gravity.TipGravity;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.multimodalinput.event.TouchEvent;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 弹出卡片对话框效果测试
 *
 * @author 王浩 邮件:bingoogolapple@gmail.com
 * @since 2021-04-25
 */
public class TestActivity extends AbilitySlice {
    private static final int WIDTH_TRANSFORMERS_TIP = 300;

    private static final int HEIGHT_TRANSFORMERS_TIP = 500;

    private static final int WIDTH_ARROW = 50;

    private static final int HEIGHT_ARROW = 30;

    private static final int RADIUS = 20;

    private static final int ANCHOR_LIST_COUNT = 15;

    private static final int CHIP_TEXT_SIZE = 14;

    private static final int TEXT_SIZE = 12;

    private static final int PADDING = 200;

    private static final int TWO = 2;

    private static final float VIEW_ALPHA_DONE = 0.8F;

    private static final float VIEW_ALPHA_UP = 0.3F;

    private List<Component> mAnchorList;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_activity_test);
        initAnchorList();
        initGravityDemo();
    }

    private void initAnchorList() {
        mAnchorList = new ArrayList<>();
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_one));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_two));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_three));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_four));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_five));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_six));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_seven));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_eight));
        mAnchorList.add(findComponentById(ResourceTable.Id_tv_anchor_nine));
    }

    private void initGravityDemo() {
        DirectionalLayout chipGroup = (DirectionalLayout) findComponentById(ResourceTable.Id_cg_gravity);
        ArrayList listField = new ArrayList<Field>();
        for (Field field : TipGravity.class.getDeclaredFields()) {
            listField.add(field);
        }
        int chipGroupWidth = Utils.calculateScreenWidth(getContext()) - PADDING;
        for (int index = 0; index < listField.size(); ) {
            Component component = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_test_tip_text, null, false);
            Text chip1 = (Text) component.findComponentById(ResourceTable.Id_tip_text);
            Text chip2 = null;
            chip1.setTextSize(CHIP_TEXT_SIZE, Text.TextSizeType.FP);

            Field field1 = (Field) listField.get(index);
            Field field2 = null;
            if (listField.size() > index + 1) {
                field2 = (Field) listField.get(index + 1);
            }
            chip1.setText(field1.getName());
            int chipWidth1 = calculateTextWidth(chip1);
            int chipWidth2 = 0;
            if (field2 != null) {
                chip2 = (Text) component.findComponentById(ResourceTable.Id_tip_text2);
                chip2.setTextSize(CHIP_TEXT_SIZE, Text.TextSizeType.FP);
                chip2.setText(field2.getName());
                chipWidth2 = calculateTextWidth(chip2);
            }

            try {
                chip1.setTag(field1.getInt(field1.getType()));
                setTouchEventListener(chip1);
                if (field2 != null) {
                    chip2.setTag(field2.getInt(field2.getType()));
                    setTouchEventListener(chip2);
                }
            } catch (IllegalAccessException e) {
                LogUtils.log(0, "TestActivity", "IllegalAccessException");
            }
            if (chipWidth1 + chipWidth2 > chipGroupWidth) {
                index = index + 1;
            } else {
                if (field2 != null) {
                    chip2.setVisibility(Component.VISIBLE);
                }
                index = index + TWO;
            }
            chipGroup.addComponent(component);
        }
    }

    private void setTouchEventListener(Text text) {
        text.setTouchEventListener(
                new Component.TouchEventListener() {
                    @Override
                    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                        switch (touchEvent.getAction()) {
                            case TouchEvent.PRIMARY_POINT_DOWN:
                                text.setAlpha(VIEW_ALPHA_DONE);
                                break;
                            case TouchEvent.PRIMARY_POINT_UP:
                                text.setAlpha(VIEW_ALPHA_UP);
                                showTip((Integer) text.getTag());
                                break;
                            default:
                                break;
                        }
                        return true;
                    }
                });
    }

    private int calculateTextWidth(Text text) {
        Paint textPaint = new Paint();
        textPaint.setTextSize((int) text.getTextSize());
        return (int) textPaint.measureText(text.getText());
    }

    private void showTip(int tipGravity) {
        for (Component anchorView : mAnchorList) {
            Component component = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_layout_test_tip, null, false);
            TransformersTip transformersTip = newTransformersTip(anchorView, component);
            int id = anchorView.getId();

            transformersTip.setSize(WIDTH_TRANSFORMERS_TIP, HEIGHT_TRANSFORMERS_TIP);
            if (id == ResourceTable.Id_tv_anchor_one || id == ResourceTable.Id_tv_anchor_two
                    || id == ResourceTable.Id_tv_anchor_three) {
                transformersTip.setMode(LayoutAlignment.BOTTOM);
            } else {
                transformersTip.setMode(LayoutAlignment.TOP);
            }
            transformersTip.setHasArrow(true);
            transformersTip.setAutoClosable(true);
            transformersTip.setTransparent(true);
            transformersTip.setCornerRadius(RADIUS);
            transformersTip.setArrowSize(WIDTH_ARROW, HEIGHT_ARROW);
            transformersTip.setBackColor(new Color(Color.getIntColor("#CC4CAF50")));
            transformersTip.show();
        }
    }

    private TransformersTip newTransformersTip(Component anchorView, Component component) {
        TransformersTip transformersTip = new TransformersTip(anchorView, component) {
            @Override
            public boolean isTouchOutside() {
                return false;
            }

            @Override
            protected void initView(Component contentView) {
                Text tipContentTv = (Text) contentView.findComponentById(ResourceTable.Id_tv_tip_content);
                tipContentTv.setText("修改后的标题");

                ListContainer tipContentRv = (ListContainer) contentView
                        .findComponentById(ResourceTable.Id_rv_tip_content);
                tipContentRv.setItemProvider(new BaseItemProvider() {
                    @Override
                    public int getCount() {
                        return ANCHOR_LIST_COUNT;
                    }

                    @Override
                    public Object getItem(int position) {
                        return position;
                    }

                    @Override
                    public long getItemId(int position) {
                        return 0;
                    }

                    @Override
                    public Component getComponent(int position, Component component,
                                                  ComponentContainer componentContainer) {
                        Text text = new Text(getContext());
                        text.setTextSize(TEXT_SIZE, Text.TextSizeType.FP);
                        text.setText("第 " + position + " 项");
                        return text;
                    }
                });
            }
        };
        return transformersTip;
    }
}
